import styles from './index.module.scss'
import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import logo from '@/assets/images/logo.png'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions'
import { useHistory, useLocation } from 'react-router-dom'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  //跳转时携带的内容，可以通过location对象拿到
  const location = useLocation()

  const onFinish = async (values) => {
    if (!values.remember)
      return message.info('请同意「用户协议」和「隐私条款」')
    const { mobile, code } = values

    try {
      await dispatch(login({ mobile, code }))

      message.success('登录成功', 1.5, () => {
        //location.state如果有值，就跳转，没有则跳到home
        history.replace(location.state ?? '/home')
      })
    } catch (e) {
      if ('response' in e) {
        message.warn(e.response.data.message)
      } else {
        message.warn('登陆超时')
      }
    }
  }

  return (
    <div className={styles.root}>
      <div className="site-card-border-less-wrapper login-wrapper">
        <Card
          bordered={false}
          style={{
            width: 400,
          }}
        >
          <img src={logo} alt="" className="login-logo" />
          {/*
            表单校验需要添加name属性，不然不会生效表单校验
          */}
          <Form
            name="basic"
            autoComplete="off"
            validateTrigger="onBlur"
            onFinish={onFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              remember: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '手机号为必填项',
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号码',
                  validateTrigger: 'onBlur',
                },
              ]}
            >
              <Input placeholder="请输入手机号码" maxLength={11} />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码为必填项',
                },
              ]}
            >
              <Input placeholder="请输入验证码" maxLength={6} />
            </Form.Item>

            {/*
              此处需要将valuePropName的值设置为checked，
              因为，Form.item默认操作的是value属性，所以，如果Form.item的子节点的值不是value，就需要设置为他自己的值
              比如，checkbox组件操作的是checked，因此，需要将valuePropName设置为checked
            */}
            <Form.Item name="remember" valuePropName="checked">
              <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  )
}

export default Login
